package com.fanrui.code.gate.client;

import com.fanrui.code.gate.core.GateServerHandler;
import com.fanrui.code.socket.netty.client.SocketClient;
import com.fanrui.code.socket.netty.core.FieldPrepender;
import com.fanrui.code.socket.netty.core.FrameDecoder;
import com.fanrui.code.socket.netty.core.InboundExceptionLogHandler;
import com.fanrui.code.socket.netty.core.OutboundExceptionLogHandler;
import com.fanrui.proto.cmd.ServerCmdWrapper;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;

/**
 * 连接到主服务器的客户端
 * */
public class OtherServerClient extends SocketClient{
	

	
	public OtherServerClient(String ip,int port) {
		super(ip, port);
		
	}
	
	


	@Override
	protected ChannelInitializer<Channel> getChannelInitializer() {
		return new ChannelInitializer<Channel>() {

			@Override
			protected void initChannel(Channel ch) throws Exception {
				ch.pipeline()
						// .addLast("log", new LoggingHandler())
						.addLast("frame", new FrameDecoder()).addLast("field", new FieldPrepender())
						.addLast("decoder", new ProtobufDecoder(ServerCmdWrapper.getDefaultInstance()))
						.addLast("encoder", new ProtobufEncoder())
						.addLast("clientHandler", new SimpleChannelInboundHandler<ServerCmdWrapper>() {

							@Override
							protected void channelRead0(ChannelHandlerContext ctx, ServerCmdWrapper msg)
									throws Exception {
								GateServerHandler.getInstance().handlerOtherServerMessage(msg);
							}

							@Override
							public void channelInactive(ChannelHandlerContext ctx) throws Exception {
							
							}

						}).addLast("inboundException", new InboundExceptionLogHandler())
						.addLast("outboundException", new OutboundExceptionLogHandler());
			}

		};
	}
	
	/**
	 * 
	 * 发送request
	 * 
	 * @param listener
	 * @param methodName
	 * @param args
	 * @return
	 * @throws InterruptedException
	 */
	public void sendRequest(ServerCmdWrapper msg) {

		try {
			this.getConnect().writeAndFlush(msg);
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
	}

}
